package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.bean.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    @GetMapping("checked/{userId}")
    @ResponseBody
    public ResponseVo<List<Cart>> queryCheckedCarts(@PathVariable("userId")Long userId){
        List<Cart> carts = this.cartService.queryCheckedCarts(userId);
        return ResponseVo.ok(carts);
    }


    /**
     * 新增购物车，点击新增按钮，就会触发该方法
     * 传递的参数：skuId count
     * @param cart
     * @return
     */
    @GetMapping
    public String addCart(Cart cart){
        this.cartService.addCart(cart);

        return "redirect:http://cart.gmall.com/addCart.html?skuId=" + cart.getSkuId() + "&count=" + cart.getCount();
    }

    @GetMapping("addCart.html")
    public String queryCartByUserIdAndSkuId(Cart cart, Model model){
        BigDecimal count = cart.getCount();
        cart = this.cartService.queryCartByUserIdAndSkuId(cart);
        cart.setCount(count);
        model.addAttribute("cart",cart);
        return "addCart";
    }

    @GetMapping("cart.html")
    public String queryCarts(Model model){
        List<Cart> carts = this.cartService.queryCarts();
        model.addAttribute("carts",carts);
        return "cart";
    }

    @PostMapping("updateNum")
    @ResponseBody
    public ResponseVo updateNum(@RequestBody Cart cart){
        this.cartService.updateNum(cart);
        return ResponseVo.ok();
    }

    @PostMapping("deleteCart")
    @ResponseBody
    public ResponseVo deleteCart(@RequestParam("skuId")Long skuId){
        this.cartService.deleteCart(skuId);
        return ResponseVo.ok();
    }






//    @Autowired
//    private LoginInterceptor loginInterceptor;

    @GetMapping("test")
    @ResponseBody
    public String test(HttpServletRequest request){

//        System.out.println("controller方法开始执行-------------");
//        long now = System.currentTimeMillis();
//        this.cartService.executor1();
//        this.cartService.executor2();
//        System.out.println("controller方法执行完成："+(System.currentTimeMillis()-now));


//        System.out.println(this.loginInterceptor.getUserInfo());
//        System.out.println(request.getAttribute("userId"));
//        System.out.println(request.getAttribute("userKey"));
//        System.out.println(LoginInterceptor.getUserInfo());
        return "hello test";
    }


}
